import { cloneDeep } from 'lodash'
import { CHANGEMSGSTATE, DELMSG } from './actionTypes'
// 定义初始数据
let defaultState = {
  msg: [
    {
      context: '我要把你们的电都偷光！',
      hasRead: true
    },
    {
      context: '老板，什么时候发工资啊？',
      hasRead: true
    },
    {
      context: '爱酱世界第一可爱！',
      hasRead: false
    },
    {
      context: '已经没有什么好怕的了！~~',
      hasRead: false
    },
    {
      context: '这样的事，绝对很奇怪啊！',
      hasRead: false
    }
  ]
}
// 读取缓存的状态
const msgList = localStorage.getItem('msgList')
if (msgList) {
  defaultState = JSON.parse(msgList)
}
const rootReducer = (state = defaultState, action) => {
  const newState = cloneDeep(state)
  switch (action.type) {
    case CHANGEMSGSTATE:
      newState.msg[action.index].hasRead = true
      break;
    case DELMSG:
      newState.msg.splice(action.index, 1)
      break;
    default:
      break;
  }
  // 保存修改的状态
  localStorage.setItem('msgList', JSON.stringify(newState))
  return newState
}

export default rootReducer
